<?php
namespace app\common\logic;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

//工具类
class Qiniu
{
    private $config;
    private $plugin;
    private $storageRoot;
    
    public function __construct(){
        $pluginClass = cmf_get_plugin_class('Qiniu');
        $this->plugin = new $pluginClass();
        $this->config = $this->plugin->getConfig();
        $this->storageRoot = $this->config['protocol'] . '://' . $this->config['domain'] . '/';
    }
    
    public function index($filePath){
        $arr = parse_url($filePath);
        $arr2 = pathinfo($arr['path'],PATHINFO_EXTENSION);//后缀
        // 上传到七牛后保存的文件名
        $key = $this->create_unique().'.'.$arr2;
        //halt($key);
        //var_dump($this->config);
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $watermark = $this->config['styles_watermark'];
        $upManager = new UploadManager();
        $auth      = new Auth($accessKey, $secretKey);
        $token     = $auth->uploadToken($this->config['bucket']);
         //var_dump($token);die;
        $result = $upManager->putFile($token, $key, $filePath);

        $url        = $this->getImageUrl($key, $watermark);
        return $url;
    }


    /**
     * 获取图片地址
     * @param string $file
     * @param string $style
     * @return mixed
     */
    public function getImageUrl($file, $style = 'watermark')
    {
        $config = $this->config;
        $url    = $this->storageRoot . $file;

       /* if (!empty($style)) {
            $url = $url . $config['style_separator'] . $style;
        }*/

        return $url;
    }

    //生成文件名
    function create_unique() {
        $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']
         .time() . rand();
        return sha1($data);
    }

    public function getObject(){
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $auth      = new Auth($accessKey, $secretKey);
        // 配置
        $config = new \Qiniu\Config();
        
        $BucketManager = new BucketManager($auth);
        return $BucketManager;
    }

    public function getBucket(){
        return $this->config['bucket'];
    }
    
    public function delete($key){
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $auth      = new Auth($accessKey, $secretKey);
        // 配置
        $config = new \Qiniu\Config();
        
        $BucketManager = new BucketManager($auth);


        $rs = $BucketManager->delete($this->config['bucket'],$key);
        return $rs;
    }

}
	
